﻿using OWork.ICloudEn.ClientContainer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace NET60WpfSimpleStart {
    public partial class FormStart : Form {
        private string[] AppStartArgs;
        public FormStart(string[] args) {
            AppStartArgs = args;
            InitializeComponent();
        }

        private void FormStart_Load(object sender, EventArgs e) {
            //启动时,直接检查是否激活

            //检测是否有参数传入加载指定加密包
            var loadEPArg = AppStartArgs.FirstOrDefault(arg => arg.StartsWith("-loadEPKey:"));
            var loadEPKey = loadEPArg?.Substring("-loadEPKey:".Length);
            CCManager.Init(
                "7c7ef166aa1340bf8a5485bf7e54279b",
                "<RSAKeyValue><Modulus>r5RAQpcjNV927mZdheD3DpHBEwPChuWnhipc9Jf16SkBwV/CZHlmpTkXWCPGSZ0lUhW1dW4Tvxd+/JwX9fmZ6rf4zxLow/jfWB07ZfDyDrYOUYZNUAAZVvXZd/tRJ0x390elafHMtYG4aHdSXF0On5rWSH4Lc+4BeTsURDlZWIU=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>",
                loadEPKey);

            var loadSuccess = false;

            if (AppStartArgs.Contains("-debugLoadAssembly")) {
                //如果是调试模式,则直接加载同目录下的dll
                var dllDir = Path.GetDirectoryName(typeof(FormStart).Assembly.Location);
                var assembly = Assembly.LoadFile(Path.Combine(dllDir, "NET60WpfSimpleMain.dll"));
                CCManager.EntryPointAssembly = assembly;
                loadSuccess = true;
            } else {
                if (CCManager.HasActivate()) {
                    var loadResult = CCManager.LoadAssemblys();
                    if (loadResult.Success) {
                        loadSuccess = true;
                    }
                }
            }


            if (loadSuccess) {
                //加载成功,则隐藏启动窗口
                Hide();
            } else {
                //没加载成功,则需要弹出激活窗口
                var win = new FormActivate();
                if (win.ShowDialog() != DialogResult.OK || win.ResultAssemblys == null) {
                    //不激活,则退出程序
                    Close();
                    return;
                }
            }

            var startType = CCManager.EntryPointAssembly.GetType("NET60WpfSimpleMain.StartHelper");
            var runMethod = startType.GetMethod("Run");
            //使用模态窗口启动
            runMethod.Invoke(null, new object[] { AppStartArgs });
            //到这里说明模态窗口已经关闭,则正常退出程序
            Close();
        }
    }
}
